import React from 'react';
import Item from './Item';

export class List extends React.Component {
  constructor() {
    super();
    this.state = {
      list: [
        {
          id: 1,
          name: '超级好吃的棒棒糖',
          price: 18.8,
          info: '开业大酬宾，全场8折',
        },
        {
          id: 2,
          name: '超级好吃的大鸡腿',
          price: 34.2,
          info: '开业大酬宾，全场8折',
        },
        {
          id: 3,
          name: '超级无敌的冰激凌',
          price: 14.2,
          info: '开业大酬宾，全场8折',
        },
      ],
    };
  }

  // 砍价函数
  kan = (id, step) => {
    console.log(id, step);
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return { ...item, price: (item.price - step).toFixed(2) };
      } else {
        return item;
      }
    });
    // 设置页面数据
    this.setState({
      list: newList,
    });
  };

  render() {
    return (
      <div style={{ width: '80%', padding: 10, border: '2px solid black' }}>
        <h2>父组件</h2>
        {this.state.list.map((item) => (
          <Item
            // 注意这里的key是虚拟DOM做diff用的，并不能在子组件中使用
            key={item.id}
            id={item.id}
            name={item.name}
            price={item.price}
            info={item.info}
            kan={this.kan}
          />
        ))}
      </div>
    );
  }
}

export default List;
